package edu.hrbu.trade01.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.hrbu.trade01.annotation.MyLog;
import edu.hrbu.trade01.entity.User;
import edu.hrbu.trade01.service.UserService;
import edu.hrbu.trade01.util.R;
import edu.hrbu.trade01.util.TableR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static edu.hrbu.trade01.util.ConstUtil.*;

/**
 * @author 徐登宇
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 条件分页查询
    @RequestMapping("/list")
    public TableR list(@RequestParam(value = "page", defaultValue = "1") int page,
                       @RequestParam(value = "limit", defaultValue = "5") int limit,
                       @RequestParam(value = "searchParams", required = false) String userStr) {
        Page<User> pageModel = userService.getPageWithCondition(page, limit, userStr);
        return TableR.ok(pageModel.getTotal(), pageModel.getRecords());
    }

    @MyLog(title = LOG_TITLE_SAVE, businessType = LOG_TYPE_SYS)
    @PostMapping("/save")
    public R save(@RequestBody User user) {
        boolean f = userService.check(user);
        if (!f) {
            throw new RuntimeException("用户名已存在！");
        }
        userService.save(user);
        return R.ok();
    }

    @MyLog(title = LOG_TITLE_DEL, businessType = LOG_TYPE_SYS)
    @PostMapping("/remove")
    public R remove(@RequestParam("id") Long id) {
        userService.removeById(id);
        return R.ok();
    }

    @MyLog(title = "批量删除", businessType = LOG_TYPE_SYS)
    @PostMapping("/removeBatch")
    public R removeBatch(@RequestParam("ids")List<Long> ids) {
        userService.removeBatchByIds(ids);
        return R.ok();
    }

    @MyLog(title = LOG_TITLE_UPDATE, businessType = LOG_TYPE_SYS)
    @PostMapping("/update")
    public R update(@RequestBody User user) {
        boolean f = userService.check(user);
        if (!f) {
            throw new RuntimeException("用户名已存在！");
        }
        userService.updateById(user);
        return R.ok();
    }

}
